package com.zdlee.netty.server11.server;

import com.zdlee.netty.server11.server.handler.inbound.InBoundHandlerA;
import com.zdlee.netty.server11.server.handler.inbound.InBoundHandlerB;
import com.zdlee.netty.server11.server.handler.inbound.InBoundHandlerC;
import com.zdlee.netty.server11.server.handler.outbound.OutBoundHandlerA;
import com.zdlee.netty.server11.server.handler.outbound.OutBoundHandlerB;
import com.zdlee.netty.server11.server.handler.outbound.OutBoundHandlerC;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-11-29 13:24
 */
public class NettyServer {

    private static final int PORT=8000;

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup=new NioEventLoopGroup();
        NioEventLoopGroup workerGroup=new NioEventLoopGroup();

        final ServerBootstrap serverBootstrap=new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childOption(ChannelOption.TCP_NODELAY,true )
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                      // ch.pipeline().addLast(new ServerHandler());
                        //inBound 处理读的逻辑
                        ch.pipeline().addLast(new InBoundHandlerA());
                        ch.pipeline().addLast(new InBoundHandlerB());
                        ch.pipeline().addLast(new InBoundHandlerC());

                        //outBound 处理写的逻辑
                        ch.pipeline().addLast(new OutBoundHandlerA());
                        ch.pipeline().addLast(new OutBoundHandlerB());
                        ch.pipeline().addLast(new OutBoundHandlerC());
                    }
                });

        bind(serverBootstrap,PORT);
    }

    private static void bind(final ServerBootstrap serverBootstrap,final int port){
        serverBootstrap.bind(port).addListener(future -> {
            if(future.isSuccess())
            {
                System.out.println("端口[" + port + "]绑定成功!");
            }else
            {
                System.err.println("端口[" + port + "]绑定失败!");
            }
        });
    }

}
